package com.mjh.config.handler;

import com.mjh.constant.AuthConstants;
import com.mjh.model.R;
import com.mjh.utils.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登出成功处理器
     *
     * @param request HttpServletRequest对象，用于获取请求信息，如请求头
     * @param response HttpServletResponse对象，用于向客户端发送响应
     * @param authentication Authentication对象，包含用户认证信息
     * @throws IOException 如果在写入响应时发生I/O错误
     * @throws ServletException 如果请求处理过程中发生Servlet相关的错误
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取请求头中的Authorization值
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        // 移除"Bearer"前缀，获取纯JWT token
        String jwt_token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
        // 从Redis中删除对应的token，以完成注销操作
        stringRedisTemplate.delete(AuthConstants.TOKEN_REDIS_KEY_PREFIX + jwt_token);
        // 向客户端发送成功登出的响应
        ResponseUtils.write(response, R.OK("登出成功"));
    }
}
